package de.breitbeil.jbooking.util;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Observable;

import org.springframework.binding.value.ValueModel;
import org.springframework.core.closure.Constraint;

import de.breitbeil.jbooking.domain.Booking;
import de.breitbeil.jbooking.domain.Person;

public class PersonFilter extends Observable implements Constraint, PropertyChangeListener {

    private ValueModel personValueModel;
    
    public PersonFilter(ValueModel personValueModel) {
        this.personValueModel = personValueModel;
    }
    
    public void propertyChange(PropertyChangeEvent evt) {
        setChanged();
        notifyObservers(evt.getNewValue());
        clearChanged();
    }

    public boolean test(Object argument) {
        // allow empty selection
        if(argument == null) {
            return true;
        }

        if(argument instanceof Booking) {
            Booking booking = (Booking) argument;
            Person selectedPerson = (Person) personValueModel.getValue();

            if(selectedPerson == null || booking == null || booking.getPerson() == null) {
                return false;
            }

            return selectedPerson.equals(booking.getPerson());
        }
        return false;
    }
}
